<template>
  <a-card :bordered="false">
    <a-tabs v-model="activeKey" @change="handleChangeTab">
      <a-tab-pane key="tempSave" tab="暂存中">
        <div class="table-operator" style="margin-top: 10px; margin-bottom: 14px">
          <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
        </div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          <span style="float: right">
            <a-popover title="自定义列" trigger="click" placement="leftBottom">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row style="width: 400px">
                    <template v-for="(item, index) in defColumns">
                      <template v-if="item.key !== 'rowIndex' && item.dataIndex !== 'action'">
                        <a-col :span="12"
                          ><a-checkbox :value="item.dataIndex"
                            ><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox
                        ></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />设置</a>
            </a-popover>
          </span>
        </div>
        <a-table
          ref="tempSaveTable"
          size="middle"
          bordered
          rowKey="id"
          class="j-table-force-nowrap"
          :scroll="{ x: true }"
          :columns="columns"
          :dataSource="tempSaveTable.dataSource"
          :pagination="{
            ...tempSaveTable.ipagination,
            onChange: handleTempSavePageChange, // 监听页码变化
            onShowSizeChange: handleTempSavePageSizeChange, // 监听每页数量变化
          }"
          :loading="tempSaveTable.loading"
          :customRow="rowSelect"
        >
          <span slot="action" slot-scope="text, record">
            <a @click="handleEdit(record)">编辑</a>
            <act-apply-btn
              v-if="record.approvalFlow > 0"
              @success="loadData"
              :data-id="record.id"
              :serviceName="serviceName"
              :variables="record"
            ></act-apply-btn>
            <a-divider v-else type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="handleDetail(record)">详情</a>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="needEdit" tab="需修改">
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          <span style="float: right">
            <a-popover title="自定义列" trigger="click" placement="leftBottom">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row style="width: 400px">
                    <template v-for="(item, index) in defColumns">
                      <template v-if="item.key !== 'rowIndex' && item.dataIndex !== 'action'">
                        <a-col :span="12"
                          ><a-checkbox :value="item.dataIndex"
                            ><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox
                        ></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />设置</a>
            </a-popover>
          </span>
        </div>
        <a-table
          ref="needEditTable"
          size="middle"
          bordered
          rowKey="id"
          class="j-table-force-nowrap"
          :scroll="{ x: true }"
          :columns="columns"
          :dataSource="needEditTable.dataSource"
          :pagination="{
            ...needEditTable.ipagination,
            onChange: handleNeedEditPageChange, // 监听页码变化
            onShowSizeChange: handleNeedEditPageSizeChange, // 监听每页数量变化
          }"
          :loading="needEditTable.loading"
          :customRow="rowSelect"
        >
          <span slot="action" slot-scope="text, record">
            <a @click="handleEdit(record)">编辑</a>
            <act-apply-btn
              @success="loadData"
              :data-id="record.id"
              :serviceName="serviceName"
              :variables="record"
              text="重新提交"
            ></act-apply-btn>
            <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="handleDetail(record)">详情</a>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="approving" tab="审批中">
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          <span style="float: right">
            <a-popover title="自定义列" trigger="click" placement="leftBottom">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row style="width: 400px">
                    <template v-for="(item, index) in defColumns">
                      <template v-if="item.key !== 'rowIndex' && item.dataIndex !== 'action'">
                        <a-col :span="12"
                          ><a-checkbox :value="item.dataIndex"
                            ><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox
                        ></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />设置</a>
            </a-popover>
          </span>
        </div>
        <a-table
          ref="approvingTable"
          size="middle"
          bordered
          rowKey="id"
          class="j-table-force-nowrap"
          :scroll="{ x: true }"
          :columns="columns"
          :dataSource="approvingTable.dataSource"
          :pagination="{
            ...approvingTable.ipagination,
            onChange: handleApprovingPageChange, // 监听页码变化
            onShowSizeChange: handleApprovingPageSizeChange, // 监听每页数量变化
          }"
          :loading="approvingTable.loading"
          :customRow="rowSelect"
        >
          <span slot="action" slot-scope="text, record">
            <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
            <a-divider type="vertical" />
            <a @click="handleDetail(record)">详情</a>
            <a-divider v-if="record.actStatus != '撤回'" type="vertical" />
            <a v-if="record.actStatus != '撤回'" @click="handleStop(record)">取消申请</a>
          </span>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="approved" tab="已审批">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper" style="margin-top: 10px">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :xl="10" :lg="11" :md="12" :sm="24">
                <a-form-item label="制单日期">
                  <j-date
                    date-format="YYYY-MM-DD"
                    placeholder="请选择开始日期"
                    class="query-group-cust"
                    v-model="createTime_begin"
                  ></j-date>
                  <span class="query-group-split-cust"></span>
                  <j-date
                    date-format="YYYY-MM-DD"
                    placeholder="请选择结束日期"
                    class="query-group-cust"
                    v-model="createTime_end"
                  ></j-date>
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          <span style="float: right">
            <a-popover title="自定义列" trigger="click" placement="leftBottom">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row style="width: 400px">
                    <template v-for="(item, index) in defColumns">
                      <template v-if="item.key !== 'rowIndex' && item.dataIndex !== 'action'">
                        <a-col :span="12"
                          ><a-checkbox :value="item.dataIndex"
                            ><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox
                        ></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />设置</a>
            </a-popover>
          </span>
        </div>
        <!-- 查询区域-END -->
        <a-table
          ref="approvedTable"
          size="middle"
          bordered
          rowKey="id"
          class="j-table-force-nowrap"
          :scroll="{ x: true }"
          :columns="columns"
          :dataSource="approvedTable.dataSource"
          :pagination="{
            ...approvedTable.ipagination,
            onChange: handleApprovedPageChange, // 监听页码变化
            onShowSizeChange: handleApprovedPageSizeChange, // 监听每页数量变化
          }"
          :loading="approvedTable.loading"
          :customRow="rowSelect"
        >
          <span slot="action" slot-scope="text, record">
            <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
            <a-divider type="vertical" />
            <a @click="handleDetail(record)">详情</a>
            <a-divider type="vertical" />
            <a @click="printPreview(record)">单据打印</a>
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <a-tabs>
      <a-tab-pane tab="领料明细" :key="subActiveKey" :forceRender="true">
        <j-vxe-table
          keep-source
          ref="tslSamplePickBillDetailTable"
          :loading="tslSamplePickBillDetailTable.loading"
          :columns="tslSamplePickBillDetailTable.columns"
          :dataSource="tslSamplePickBillDetailTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :rowSelection="false"
          :toolbar="false"
        />
      </a-tab-pane>
    </a-tabs>
    <tsl-sample-pick-bill-modal ref="modalForm" @ok="modalFormOk" />
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import TslSamplePickBillModal from './modules/TslSamplePickBillModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import '@/assets/less/TableExpand.less'
import { getAction, httpAction } from '@api/manage'
import ActApplyBtn from '@views/flowable/components/ActApplyBtn.vue'
import ActHistoricDetailBtn from '@views/flowable/components/ActHistoricDetailBtn.vue'
import { deepClone, getDate } from '@/utils'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import store from '@/store'

export default {
  name: 'TslSamplePickBillList',
  mixins: [JeecgListMixin],
  components: {
    TslSamplePickBillModal,
    ActApplyBtn,
    ActHistoricDetailBtn,
  },
  data() {
    return {
      description: '样品领料单管理页面',
      selectedCode: '',
      subActiveKey: 'detail',
      serviceName: 'tslSamplePickBillService',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '样品领料单号',
          align: 'center',
          dataIndex: 'code',
          sorter: (a, b) => a.code.localeCompare(b.code, 'en'),
        },
        {
          title: '领料人',
          align: 'center',
          dataIndex: 'pickBy',
        },
        {
          title: '领料部门',
          align: 'center',
          dataIndex: 'pickOrgCode_dictText',
        },
        {
          title: '领料日期',
          align: 'center',
          dataIndex: 'pickDate',
          sorter: (a, b) => a.pickDate.localeCompare(b.pickDate, 'en'),
        },
        {
          title: '制单人',
          align: 'center',
          dataIndex: 'createBy_dictText',
        },
        {
          title: '制单部门',
          align: 'center',
          dataIndex: 'sysOrgCode_dictText',
        },
        {
          title: '制单日期',
          align: 'center',
          dataIndex: 'createTime',
          sorter: (a, b) => a.createTime.localeCompare(b.createTime, 'en'),
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customerId_dictText',
        },
        {
          title: '流程状态',
          align: 'center',
          dataIndex: 'actStatus',
        },
        {
          title: '待处理节点',
          align: 'center',
          dataIndex: 'taskName',
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      tslSamplePickBillDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '客户物料编码',
            key: 'customCode',
            type: JVXETypes.normal,
            align: 'center',
            width: '140px',
            defaultValue: '',
          },
          {
            title: '物料编码',
            align: 'center',
            dataIndex: 'productCode',
            key: 'productCode',
            type: JVXETypes.normal,
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'productBatchNo',
            key: 'productBatchNo',
            type: JVXETypes.normal,
          },
          {
            title: '规格型号',
            align: 'center',
            dataIndex: 'materialSpec',
            key: 'materialSpec',
            type: JVXETypes.normal,
          },
          {
            title: '主单位',
            align: 'center',
            dataIndex: 'meUnit_dictText',
            dictCode: 'ji_unit',
            key: 'meUnit_dictText',
            type: JVXETypes.normal,
          },
          {
            title: '申请数量',
            align: 'center',
            dataIndex: 'applyQuantity',
            key: 'applyQuantity',
            type: JVXETypes.normal,
          },
          {
            title: '备注',
            align: 'center',
            dataIndex: 'remark',
            key: 'remark',
            type: JVXETypes.normal,
          },
        ],
      },
      approvedTable: {
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        dataSource: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
      },
      approvingTable: {
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        dataSource: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
      },
      needEditTable: {
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        dataSource: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
      },
      tempSaveTable: {
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        dataSource: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
      },
      activeKey: 'tempSave',
      url: {
        list: '/pro/tslSamplePickBill/list',
        editById: '/pro/tslSamplePickBill/editById',
        detailList: '/pro/tslSamplePickBill/queryTslSamplePickBillDetailByMainId',
        delete: '/pro/tslSamplePickBill/delete',
        deleteBatch: '/pro/tslSamplePickBill/deleteBatch',
        exportXlsUrl: '/pro/tslSamplePickBill/exportXls',
        importExcelUrl: 'pro/tslSamplePickBill/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
      settingColumns: [],
    }
  },
  created() {
    this.createTime_begin = getDate('day', -7)
    this.createTime_end = getDate('day', 0)
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    handleSubmit(record) {
      record.status = 999
      httpAction(this.url.editById, record, 'PUT').then((res) => {
        if (res.success) {
          this.$message.success('编辑成功！')
          this.activeKey = 'approved'
          this.loadData()
        }
      })
    },
    rowSelect(record, index) {
      return {
        on: {
          click: (event) => {
            let params = { id: record.id }
            this.loadDetailData(params)
          },
        },
      }
    },
    loadDetailData(params) {
      this.tslSamplePickBillDetailTable.dataSource = []
      this.tslSamplePickBillDetailTable.loading = true
      getAction(this.url.detailList, params).then((res) => {
        this.tslSamplePickBillDetailTable.loading = false
        if (res.success) {
          this.tslSamplePickBillDetailTable.dataSource = res.result
        }
      })
    },
    // 暂存中页：处理页码变化
    handleTempSavePageChange(page, pageSize) {
      this.tempSaveTable.ipagination.current = page
      this.tempSaveTable.ipagination.pageSize = pageSize
      this.loadTempSaveData()
    },
    // 暂存中页：处理每页数量变化
    handleTempSavePageSizeChange(page, pageSize) {
      this.tempSaveTable.ipagination.current = page
      this.tempSaveTable.ipagination.pageSize = pageSize
      this.loadTempSaveData()
    },
    // 暂存中页：处理页码变化
    handleNeedEditPageChange(page, pageSize) {
      this.needEditTable.ipagination.current = page
      this.needEditTable.ipagination.pageSize = pageSize
      this.loadNeedEditData()
    },
    // 暂存中页：处理每页数量变化
    handleNeedEditPageSizeChange(page, pageSize) {
      this.needEditTable.ipagination.current = page
      this.needEditTable.ipagination.pageSize = pageSize
      this.loadNeedEditData()
    },
    // 暂存中页：处理页码变化
    handleApprovingPageChange(page, pageSize) {
      this.approvingTable.ipagination.current = page
      this.approvingTable.ipagination.pageSize = pageSize
      this.loadApprovingData()
    },
    // 暂存中页：处理每页数量变化
    handleApprovingPageSizeChange(page, pageSize) {
      this.approvingTable.ipagination.current = page
      this.approvingTable.ipagination.pageSize = pageSize
      this.loadApprovingData()
    },
    // 已审批页：处理页码变化
    handleApprovedPageChange(page, pageSize) {
      this.approvedTable.ipagination.current = page
      this.approvedTable.ipagination.pageSize = pageSize
      this.loadApprovedData()
    },
    // 已审批页：处理每页数量变化
    handleApprovedPageSizeChange(page, pageSize) {
      this.approvedTable.ipagination.current = page
      this.approvedTable.ipagination.pageSize = pageSize
      this.loadApprovedData()
    },
    handleChangeTab() {
      this.tslSamplePickBillDetailTable.dataSource = []
      switch (this.activeKey) {
        case 'tempSave':
          this.loadTempSaveData()
          break
        case 'needEdit':
          this.loadNeedEditData()
          break
        case 'approving':
          this.loadApprovingData()
          break
        case 'approved':
          this.loadApprovedData()
          console.log('approved')
          break
        case 'closed':
          this.loadClosedData()
          console.log('closed')
          break
        default:
          break
      }
    },
    loadTempSaveData() {
      this.tempSaveTable.loading = true
      this.queryParam.status = -2
      getAction(this.url.list, this.queryParam)
        .then((res) => {
          if (res.success) {
            this.tempSaveTable.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.tempSaveTable.ipagination.total = res.result.total
            } else {
              this.tempSaveTable.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.tempSaveTable.loading = false
        })
    },
    loadNeedEditData() {
      this.needEditTable.loading = true
      this.queryParam.status = -1
      getAction(this.url.list, this.queryParam)
        .then((res) => {
          if (res.success) {
            this.needEditTable.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.needEditTable.ipagination.total = res.result.total
            } else {
              this.needEditTable.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.needEditTable.loading = false
        })
    },
    loadApprovingData() {
      this.approvingTable.loading = true
      this.queryParam.status = 0
      getAction(this.url.list, this.queryParam)
        .then((res) => {
          if (res.success) {
            this.approvingTable.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.approvingTable.ipagination.total = res.result.total
            } else {
              this.approvingTable.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.approvingTable.loading = false
        })
    },
    loadApprovedData() {
      this.approvedTable.loading = true
      let param = {
        status: 999,
        createTime_begin: this.createTime_begin,
        createTime_end: this.createTime_end,
      }
      getAction(this.url.list, param)
        .then((res) => {
          if (res.success) {
            this.approvedTable.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.approvedTable.ipagination.total = res.result.total
            } else {
              this.approvedTable.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.approvedTable.loading = false
        })
    },
    async loadData() {
      //分别根据单据状态查询结果并将其放在
      this.queryParam = this.getQueryParams()
      this.handleChangeTab()
    },
    printPreview(record) {
      let token = store.getters.token
      let id = record.id
      window.open(`${window._CONFIG['domianURL']}/jmreport/view/1098811186598989824?token=${token}&id=${id}`, '_blank')
    },
    handleStop(row) {
      const params = {
        instanceId: row.processInstanceId,
      }
      stopProcess(params).then((res) => {
        this.$message.success(res.message)
        this.loadData()
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
::v-deep .ant-table-tbody tr {
  height: 36px !important;
}
</style>
